package top.dimples.controller.admin;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import top.dimples.common.ApiResponse;
import top.dimples.common.Status;
import top.dimples.model.UserProfile;
import top.dimples.service.CaptchaService;
import top.dimples.service.RoleService;
import top.dimples.service.UserProfileService;
import top.dimples.service.UserRoleService;
import top.dimples.vo.common.PageResult;
import top.dimples.vo.user.UserListVO;
import top.dimples.vo.user.UserLoginVO;
import top.dimples.vo.user.UserProfileVO;

import javax.validation.Valid;

/**
 * @author Dimples_YJ
 * @date 2021/12/14
 */
@Api(tags = "用户模块")
@RestController
@RequestMapping("/admin/user")
public class UserAdminController {

    @Autowired
    private UserProfileService userProfileService;

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private RoleService roleService;


    /**
     * 验证码 service
     */
    @Autowired
    private CaptchaService captchaService;

    @ApiOperation(value = "分页获取用户信息", response = PageResult.class)
    @GetMapping("/list")
    public ApiResponse getUserList(UserListVO userListVO) {
        Page<UserProfile> page = userProfileService.page(new Page<>(userListVO.getPageNum(), userListVO.getPageSize()),
                new LambdaQueryWrapper<UserProfile>()
                        .eq(StrUtil.isNotEmpty(userListVO.getNickName()),
                                UserProfile::getNickName, userListVO.getNickName()));
        IPage<UserProfileVO> userList = page.convert(userProfile -> Convert.convert(UserProfileVO.class, userProfile));
        PageResult<UserProfileVO> result = PageResult.startPage(userList);
        return ApiResponse.ofSuccess(result);
    }

    @ApiOperation(value = "根据id获取用户信息", response = UserProfileVO.class)
    @GetMapping("/{id}")
    public ApiResponse getUser(@PathVariable("id") String id) {
        UserProfile userProfile = userProfileService.getById(id);
        return ApiResponse.ofSuccess(Convert.convert(UserProfileVO.class, userProfile));
    }


    @ApiOperation(value = "更新用户信息")
    @ApiOperationSupport(ignoreParameters = {"userProfileVO.roles"})
    @PutMapping("/update")
    public ApiResponse updateUser(@RequestBody UserProfileVO userProfileVO) {
        return userProfileService.updateById(Convert.convert(UserProfile.class, userProfileVO))
                ? ApiResponse.ofSuccess()
                : ApiResponse.ofStatus(Status.ERROR);
    }


    @ApiOperation(value = "用户登陆")
    @PostMapping("/login")
    public ApiResponse userLogin(@RequestBody @Valid UserLoginVO userLoginVO) {

        if (!"0000".equals(userLoginVO.getCode())) {
            // 1、检查验证码，验证后并删除
            Boolean isValidated = captchaService.validateCode(userLoginVO.getKey(), userLoginVO.getCode());
            captchaService.removeCode(userLoginVO.getKey());
            if (!isValidated) {
                return ApiResponse.of(Status.BAD_REQUEST.getCode(), "验证码不存在", null);
            }
        }
        // 2、对比用户名和密码
        LambdaQueryWrapper<UserProfile> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserProfile::getUsername, userLoginVO.getUsername()).or().eq(UserProfile::getEmail, userLoginVO.getUsername());
        queryWrapper.eq(UserProfile::getPassword, SecureUtil.md5(userLoginVO.getPassword()));
        UserProfile userProfile = userProfileService.getOne(queryWrapper);
        // 3、创建 Token
        return userProfileService.login(userProfile);
    }

    @ApiOperation(value = "退出登录")
    @GetMapping("/logout")
    public ApiResponse userLogout() {
        return ApiResponse.ofSuccess();
    }


}
